package com.blb.community.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.blb.community.entity.SysUser;
import com.blb.community.entity.vo.SysUserVO;
import com.blb.community.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @Author 帅帅
 * @Date 2022/7/12 11:22
 * @PackageName:com.blb.community.utils
 * @ClassName: EasyExcelUtil
 * @Description: EasyExcel工具类
 * @Version 1.0
 */
@Slf4j
public class EasyExcelUtil {

    public static void write(List<?> list, Class<?> t, HttpServletResponse response) {
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        try {
            response.setContentType("application/vnd.ms-excel; charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename");
            EasyExcel.write(response.getOutputStream(), t).sheet().doWrite(list);

        } catch (IOException e) {
            e.printStackTrace();

        }

    }


    public static <t> void reade(InputStream file, Class<?> t, Object o) {
        Integer temp = 0;
        EasyExcel.read(file, t, new ReadListener<t>() {
            /**
             * 单次缓存的数据量
             */
            public static final int BATCH_COUNT = 100;

            /**
             *临时存储
             */
            private List<t> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

            @Override
            public void invoke(t data, AnalysisContext context) {
                cachedDataList.add(data);
                if (cachedDataList.size() >= BATCH_COUNT) {
                    saveData();
                    // 存储完成清理 list
                    cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                saveData();
            }

            /**
             * 加上存储数据库
             */
            private void saveData() {
                if (o instanceof ISysUserService) {
                    ISysUserService sysUserService = (ISysUserService) o;
                    for (SysUser sysUser : (List<SysUser>) cachedDataList) {
                        sysUserService.save(sysUser);
                    }


                }
            }
        }).sheet().doRead();


    }

}
